package br.ita.comp.ces22.quiz.email;

import org.subethamail.wiser.Wiser;

import br.ita.comp.ces22.quiz.email.adapter.commons.CommonsEmailAdapterImpl;

public class EmailManager {
	private Wiser server;
	private CommonsEmailAdapterImpl emailAdapter;

	public EmailManager(){
		try {
			emailAdapter = new CommonsEmailAdapterImpl();
			emailAdapter.setHostName(PropertiesLoader.getField("hostname"));
			emailAdapter.setSmtpPort(new Integer(PropertiesLoader.getField("serverport")));
			emailAdapter.setFromAddress(PropertiesLoader.getField("fromaddress"));
			emailAdapter.setFromName(PropertiesLoader.getField("fromname"));
			emailAdapter.setUserName(PropertiesLoader.getField("username"));
			emailAdapter.setPassword(PropertiesLoader.getField("password"));
			emailAdapter.setUsingTLS(new Boolean(PropertiesLoader.getField("tls")));
			emailAdapter.setUsingSSL(new Boolean(PropertiesLoader.getField("ssl")));
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void send(String toMail, String errorMessage){
		try {
			String mailMessage = createMessageBody(errorMessage);
			startMailServer();
			emailAdapter.sendEmail(toMail, mailMessage, PropertiesLoader.getField("subject"), null);
			
			stopMailServer();
			Thread.sleep(2000L);
			server = null;
		} catch (InterruptedException ex){
			ex.printStackTrace();
		} catch (Exception ex){
			ex.printStackTrace();
		}
	}
	
	private String createMessageBody(String errorMessage){
		StringBuffer mailMessage = new StringBuffer();
		mailMessage.append("<html><body>");
		mailMessage.append("<p color=\"red\">");
		mailMessage.append(errorMessage);
		mailMessage.append("</p>");
		mailMessage.append("</body></html>");
	
		return mailMessage.toString();
	}
	
	private void startMailServer() throws Exception {
		if (isMailServerStopped()) {
			server = new Wiser();
			server.setPort(emailAdapter.getSmtpPort());
			server.start();
		}
	}

	private void stopMailServer() {
		if (!isMailServerStopped()) {
			server.stop();
		}
	}

	private boolean isMailServerStopped() {
		if (server == null) return true;
		return !server.getServer().isRunning();
	}
}
